package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void save(Role role, Long[] ids) {
        //除了往role表插入数据
        roleMapper.insert(role);
        //还要往中间表插入数据
        if (ids != null && ids.length > 0) {
            for (Long permissionId : ids) {

                roleMapper.insertRelation(role.getId(), permissionId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Role role, Long[] ids) {
        roleMapper.updateByPrimaryKey(role);
        roleMapper.deleteRelation(role.getId());
        insertRelation(role, ids);
    }

    @Override
    public Role selectOne(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public List<Role> queryForData(QueryObject qo) {
        return roleMapper.queryForData(qo);
    }

    @Override
    public PageInfo<Role> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Role> roles = roleMapper.queryForData(qo);
        return new PageInfo<>(roles);

        /*int count = roleMapper.queryForCount(qo);
        return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),count,
                count == 0 ?
                Collections.emptyList() : roleMapper.queryForData(qo));*/
    }

    @Override
    public List<Role> otherSqlByRoleId(Long id) {
        return roleMapper.otherSqlByRoleId(id);
    }

    /*@Override
    public int queryForCount(QueryObject qo) {
        int totalCount = roleMapper.queryForCount(qo);
        return totalCount;
    }*/

    private void insertRelation(Role role, Long[] ids) {
        if (ids != null && ids.length > 0) {
            for (long roleId : ids) {
                //往中间表中插入关系数据
                roleMapper.insertRelation(role.getId(), roleId);
            }
        }
    }
}
